package chapter_24.tcp.chat;

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;

/**
 * Created by Administrator
 * Created time 2018/8/10 15:53.
 * 案例:聊天工具(客户端)
 */
public class ChatClient {

    public static void main(String[] args) {

        System.out.println("客户端运行...");

        Thread client = new Thread(() -> {
            try (
                    // 向服务端主机对应端口发送连接请求
                    Socket socket = new Socket("127.0.0.1", 6666);
                    DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                    DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            ) {

                while (true) {
                    /*
                     发送数据
                     */
                    // 读取键盘输入的字符
                    String keyboardInputStr = bufferedReader.readLine();
                    // 结束聊天
                    if (keyboardInputStr.equalsIgnoreCase("bye")) {
                        break;
                    }

                    // 发送
                    dataOutputStream.writeUTF(keyboardInputStr);
                    dataOutputStream.flush();

                    /*
                     接收数据
                     */
                    String str = dataInputStream.readUTF();
                    // 打印接收数据
                    System.out.printf("从服务器接收的数据: [%s] \n", str);
                }

            } catch (ConnectException e) {
                System.out.println("服务器未启动!");
            } catch (IOException e) {
                System.out.println("IOException");
            }

            System.out.println("客户端停止!");
        });

        client.start();
    }
}